<template>
  <div class="relative group">
    <!-- 代码块标题栏 -->
    <div
      class="flex items-center justify-between px-4 py-2 bg-gray-800 dark:bg-gray-900 rounded-t-lg border-b border-gray-700"
    >
      <div class="flex items-center space-x-2">
        <div class="w-3 h-3 rounded-full bg-red-500"></div>
        <div class="w-3 h-3 rounded-full bg-yellow-500"></div>
        <div class="w-3 h-3 rounded-full bg-green-500"></div>
      </div>
      <div class="text-sm text-gray-400">{{ language }}</div>
      <button
        @click="copyCode"
        class="p-2 text-gray-400 hover:text-white transition-colors duration-200"
        :class="{ 'text-green-500': copied }"
      >
        <span v-if="copied" class="text-sm">已复制!</span>
        <svg
          v-else
          xmlns="http://www.w3.org/2000/svg"
          class="h-5 w-5"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"
          />
        </svg>
      </button>
    </div>
    <!-- 代码内容 -->
    <div class="relative">
      <slot></slot>
    </div>
  </div>
</template>

<script setup>
const props = defineProps({
  language: {
    type: String,
    default: "",
  },
  code: {
    type: String,
    required: true,
  },
});

const copied = ref(false);

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  } catch (err) {
    console.error("Failed to copy code:", err);
  }
};
</script>

<style scoped>
.code-block {
  @apply relative;
}

.code-block pre {
  @apply rounded-b-lg !mt-0;
}

.code-block code {
  @apply font-mono text-sm;
}
</style>
